package cool.taomu.toolkit.stock.service

import cool.taomu.toolkit.stock.dao.jooq.tables.TaomuSohuStockQuotes
import cool.taomu.toolkit.stock.dao.jooq.tables.records.TaomuSohuStockQuotesRecord
import java.util.List
import java.util.Map
import org.jooq.DSLContext
import java.math.BigDecimal
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import com.google.inject.Inject

class SohuStockService {

    @Inject
    DSLContext dsl;

    def save(Map<String, List<String>> jsonData) {
        jsonData.entrySet().forEach [ entry |
            var data = entry.getValue();

            // 创建记录并填充字段
            var TaomuSohuStockQuotesRecord record = dsl.newRecord(TaomuSohuStockQuotes.TAOMU_SOHU_STOCK_QUOTES);
            record.setCode(data.get(0) as String);
            record.setName(data.get(1) as String);
            record.setCurrentPrice(parseBigDecimal(data.get(2)));
            record.setChangePercent(data.get(3) as String);
            record.changeAmount = parseBigDecimal(data.get(4))
            record.volume = Long::parseLong(data.get(5).toString)
            record.turnover = Integer::parseInt(data.get(6).toString)
            record.circulatingMarketValue = parseBigDecimal(data.get(7))
            record.turnoverRate = data.get(8) as String
            record.peRatio = parseBigDecimal(data.get(9))
            record.highPrice = parseBigDecimal(data.get(10))
            record.lowPrice = parseBigDecimal(data.get(11))
            record.pbRatio = data.get(12) as String
            record.bidPrice = parseBigDecimal(data.get(13))
            record.askPrice = parseBigDecimal(data.get(14))
            record.detailUrl = data.get(15) as String
            record.totalMarketValue = parseBigDecimal(data.get(16))
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            record.timestamp = LocalDateTime.parse(data.get(17) as String, formatter)
            record.quoteUrl = data.get(18) as String
            // 执行 upsert（根据主键自动判断 insert or update）
            record.store(); // 如果记录已存在则 update，否则 insert
        ]
    }

    def private static BigDecimal parseBigDecimal(Object obj) {
        if(obj === null || "--".equals(obj.toString())) return null;
        return new BigDecimal(obj.toString());
    }
}
